package cn.qdu.controller;

import cn.qdu.model.Post;
import cn.qdu.model.User;
import cn.qdu.service.PostService;
import cn.qdu.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/home")
public class HomeServlet extends HttpServlet {
    private final UserService userService = new UserService();
    private final PostService postService = new PostService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("currentUser") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        try {
            // 1. 获取并更新当前用户
            User currentUser = (User) session.getAttribute("currentUser");
            currentUser = userService.getUserById(currentUser.getUserId());
            session.setAttribute("currentUser", currentUser);

            // 2. 获取动态数据（添加更多调试信息）
            List<Post> posts = postService.getPostsForUser(currentUser.getUserId(), currentUser.getUserId());
            System.out.println("[DEBUG] 获取到的动态数量: " + posts.size());

            // 在获取posts后添加以下代码：
            System.out.println("===== 数据库返回数据验证 =====");
            System.out.println("Posts类型: " + (posts == null ? "null" : posts.getClass()));
            System.out.println("Posts大小: " + (posts == null ? "null" : posts.size()));

            if (posts != null && !posts.isEmpty()) {
                Post firstPost = posts.get(0);
                System.out.println("第一条动态示例:");
                System.out.println("  PostID: " + firstPost.getPostId());
                System.out.println("  内容: " + firstPost.getContent());
                System.out.println("  作者: " + (firstPost.getUser() != null ?
                        firstPost.getUser().getNickname() : "null"));
            } else {
                System.out.println("动态列表为空或null");
            }

            // 3. 关键检查：确保数据有效
            if (posts == null) {
                System.err.println("错误: posts为null");
                posts = new ArrayList<>(); // 防止NPE
            }

            // 4. 添加更多调试属性
            request.setAttribute("posts", posts);
            request.setAttribute("debug_postsCount", posts.size());
            request.setAttribute("debug_lastPostId",
                    posts.isEmpty() ? "无" : posts.get(0).getPostId());

            // 5. 转发前确认数据
            System.out.println("[DEBUG] 即将转发到JSP，posts数量: " + posts.size());
            request.getRequestDispatcher("/views/home.jsp").forward(request, response);

        } catch (Exception e) {
            System.err.println("首页加载异常:");
            e.printStackTrace();

            // 更友好的错误处理
            request.setAttribute("errorTitle", "动态加载失败");
            request.setAttribute("errorMessage", "系统暂时无法显示动态，请稍后重试");
            request.getRequestDispatcher("/views/error.jsp").forward(request, response);
        }
    }
}